/**
 * Code a function that receives a string composed by words separated by spaces
 * and returns a string where words appear in the same order but than the
 * original string, but every word is inverted. Example, for this input string
 * 
 * @"the boy ran" the output would be
 * @"eht yob nar" Tell the complexity of the solution.
 * 
 *       http://www.careercup.com/question?id=5106757177180160
 * @author ruinvepc
 * 
 */
public class ReverseWords {

    public static String reverseWords(String source)
    {
       int s = 0;
       int end = s;
       char[] chars = source.toCharArray();
       while (s < source.length())
       {
           end = source.indexOf(' ', s);
           if (end == -1)
               end = source.length();
           reverseWords(chars, s, end);
           while(end < source.length() && chars[++end] == ' ');
           s = end;
       }
        return new String(chars);
    }


    private static void reverseWords(char[] chars, int s, int end) {
        assert end > s;
        for (int i = s, j = end-1; i < j; i++, j--)
        {
            char tmp = chars[i];
            chars[i] = chars[j];
            chars[j] = tmp;
        }
    }


    /**
     * @param args
     */
    public static void main(String[] args) {
        String source = " that  boy ran";
        System.out.println(source + " -> " + ReverseWords.reverseWords(source));

    }

}
